<template>
  <div class="Box">
    <!-- 顶部搜索/添加 -->
    <div class="SearchBox flex-LAR" v-show="tableData.length > 0">
      <el-input v-model="SearchResident.searchValue" placeholder="请输入搜索内容" class="input-with-select"
        @keyup.enter="SearchResidentList">
        <template #prepend>
          <el-select v-model="SearchResident.selectKey" style="width: 6.25rem">
            <el-option v-for="(item, index) in SearcSelect" :key="index" :label="item.label" :value="item.prop" />
          </el-select>
        </template>
        <template #append>
          <el-button class="searchBtn" :icon="Search" @click="SearchResidentList" />
        </template>
      </el-input>
      <el-button class="addBtn" type="primary" :icon="Plus" @click="handleAdd" />
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page="page.pageNum"
        v-model:limit="page.pageSize" v-model:total="page.total" :page-count="Math.ceil(page.total / page.pageSize)" />
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table class="Table" row-key="resident_id" :data="tableData" :columns="ruleTable.columns" :loading="loading"
        @selection-change="handleSelectionChange" />
    </div>
    <!-- 修改抽屉 -->
    <el-drawer v-model="editdrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in editFormColumns" :key="index" :label="item.label">
          <!-- 时间选择器 -->
          <template v-if="['date_of_birth', 'registration_date'].includes(item.prop)">
            <el-date-picker style="width: 50rem;" v-model="editform[item.prop]" type="date" />
          </template>
          <!-- 文本域 -->
          <template v-else-if="['notes'].includes(item.prop)">
            <el-input v-model="editform[item.prop]" :rows="8" type="textarea" />
          </template>
          <!-- 性别选择 -->
          <template v-else-if="['gender'].includes(item.prop)">
            <el-select v-model="editform[item.prop]">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </template>
          <!-- 家庭位置选择 -->
          <template v-else-if="['relationship'].includes(item.prop)">
            <el-select v-model="editform[item.prop]">
              <el-option label="爷爷" value="爷爷" />
              <el-option label="奶奶" value="奶奶" />
              <el-option label="父亲" value="父亲" />
              <el-option label="母亲" value="母亲" />
              <el-option label="子女" value="子女" />
            </el-select>
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="editform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>

        </cy-form-item>
        <cy-form-item>
          <!-- 操作按钮 -->
          <el-button type="primary" @click="EditSubmit">确认</el-button>
          <el-button @click="editdrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
    <!-- 添加抽屉 -->
    <el-drawer v-model="adddrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in addFormColumns" :key="index" :label="item.label">
          <!-- 时间选择器 -->
          <template v-if="['date_of_birth', 'registration_date'].includes(item.prop)">
            <el-date-picker style="width: 50rem;" v-model="addform[item.prop]" type="date" />
          </template>
          <!-- 文本域 -->
          <template v-else-if="['notes'].includes(item.prop)">
            <el-input v-model="addform[item.prop]" :rows="8" type="textarea" />
          </template>
          <!-- 性别选择 -->
          <template v-else-if="['gender'].includes(item.prop)">
            <el-select v-model="addform[item.prop]">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </template>
          <!-- 家庭位置选择 -->
          <template v-else-if="['relationship'].includes(item.prop)">
            <el-select v-model="addform[item.prop]">
              <el-option label="爷爷" value="爷爷" />
              <el-option label="奶奶" value="奶奶" />
              <el-option label="父亲" value="父亲" />
              <el-option label="母亲" value="母亲" />
              <el-option label="子女" value="子女" />
            </el-select>
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="addform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>
        </cy-form-item>
        <cy-form-item>
          <el-button type="primary" @click="AddSubmit">确认</el-button>
          <el-button @click="adddrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, watch, onMounted } from "vue";
import type { TableInstance } from "element-plus";

import CyTable from "@/components/table";
import CyForm from "@/components/form";
import CyFormItem from "@/components/form-item";

import { ElMessage, ElMessageBox, VLoad } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import {
  getResidentAllAPI,
  getResidentPageAPI,
  getResidentKeyPageAPI,
  UpdateResidentByIdAPI,
  DeleteResidentByIdAPI,
  DeleteResidentMoreByIdAPI,
  AddResidentAPI,
} from "@/api/resident";
import { assignObject } from "@/utils/object";
import { formatDate } from "@/utils/timeDajs";

const tableData: Resident[] = ref([]);
const tableRef = ref<TableInstance>();
const loading = ref(true);
const multipleSelection = ref<Resident[]>([]);
const editdrawer = ref(false);
const adddrawer = ref(false);
interface Resident {
  resident_id: number;
  family_master: string;
  name: string;
  age: string;
  gender: string;
  date_of_birth: string;
  relationship: string;
  phone: string;
  address: string;
  registration_date: string;
  notes: string;
}
const page = reactive({
  currentPage: 1,
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 筛选
const SearchResident = reactive({
  selectKey: "resident_id",
  searchValue: "",
});
// 表格配置
const ruleTable = reactive({
  columns: [
    // 全选框列
    {
      type: "selection",
      width: 55,
    },
    // 数据列
    { prop: "resident_id", label: "身份证号", width: 180 },
    { prop: "family_master", label: "户主", width: 80 },
    { prop: "name", label: "姓名", width: 80 },
    { prop: "age", label: "年龄", width: 80 },
    { prop: "gender", label: "性别", width: 80 },
    { prop: "relationship", label: "家庭位置", width: 80 },
    { prop: "phone", label: "电话" },
    { prop: "address", label: "地址" },
    { prop: "date_of_birth", label: "出生时间" },
    { prop: "registration_date", label: "登记时间" },
    { prop: "notes", label: "备注" },
    // 操作列
    {
      label: "操作",
      align: "center",
      headerRender: () => (
        <div style="text-align: center;">
          <div class="OptionsBtn" onClick={MoreDelete} style="display: inline-block;">
            批量删除
          </div>
        </div>
      ),
      render: ({ row, index }) => (
        <div>
          <el-button onClick={() => handleEdit(index, row)}>修改</el-button>
          <el-button type="danger" onClick={() => handleDelete(index, row)}>
            删除
          </el-button>
        </div>
      ),
    },
  ],
});
// 分页查询
const getResidentPage = () => {
  loading.value = true;
  getResidentPageAPI({
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "resident_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      row.forEach((item) => {
        item.date_of_birth = formatDate(item.date_of_birth);
        item.registration_date = formatDate(item.registration_date);
      });
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 选择框选中
const handleSelectionChange = (val: Resident[]) => {
  multipleSelection.value = val;
};

/* 修改 */
const editform = reactive({
  resident_id: "",
  family_master: "",
  name: "",
  age: "",
  gender: "",
  date_of_birth: "",
  relationship: "",
  phone: "",
  address: "",
  registration_date: "",
  notes: "",
});
const editFormColumns = [
  { label: "身份证号", prop: "resident_id", isReadonly: true },
  { label: "户主", prop: "family_master", isReadonly: true },
  { label: "姓名", prop: "name" },
  { label: "年龄", prop: "age" },
  { label: "性别", prop: "gender" },
  { label: "出生时间", prop: "date_of_birth" },
  { label: "家庭位置", prop: "relationship" },
  { label: "电话", prop: "phone" },
  { label: "地址", prop: "address" },
  { label: "登记时间", prop: "registration_date" },
  { label: "备注", prop: "notes" },
];
const handleEdit = (index: number, row: Resident) => {
  assignObject(editform, row);
  editdrawer.value = true;
};
// 确认修改提交
const EditSubmit = () => {
  // 时间处理
  editform.date_of_birth = formatDate(editform.date_of_birth)
  editform.registration_date = formatDate(editform.registration_date)
  // 提交后台
  UpdateResidentByIdAPI(editform).then((res) => {
    const { code, message } = res.data;
    getResidentPage();
    ElMessage.success(message);
    editdrawer.value = false;
  });
};
/* 添加 */
const addform = reactive({
  resident_id: "",
  family_master: "",
  name: "",
  age: "",
  gender: "",
  date_of_birth: "",
  relationship: "",
  phone: "",
  address: "",
  registration_date: "",
  notes: "",
});
const addFormColumns = [
  { label: "身份证号", prop: "resident_id" },
  { label: "户主", prop: "family_master" },
  { label: "姓名", prop: "name" },
  { label: "年龄", prop: "age" },
  { label: "性别", prop: "gender" },
  { label: "出生时间", prop: "date_of_birth" },
  { label: "家庭位置", prop: "relationship" },
  { label: "电话", prop: "phone" },
  { label: "地址", prop: "address" },
  { label: "登记时间", prop: "registration_date" },
  { label: "备注", prop: "notes" },
];
// 添加居民
const handleAdd = () => {
  adddrawer.value = true;
};
// 确认添加提交
const AddSubmit = () => {
  // 时间处理
  addform.date_of_birth = formatDate(addform.date_of_birth)
  addform.registration_date = formatDate(addform.registration_date)
  AddResidentAPI(addform).then((res) => {
    const { code, message } = res.data;
    ElMessage.success(message);
    adddrawer.value = false;
  });
};
/* 删除 */
const handleDelete = (index: number, row: Resident) => {
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteResidentByIdAPI(row.resident_id).then((res) => {
        const { code, message } = res.data;
        getResidentPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};
const MoreDelete = () => {
  if (!multipleSelection.value || multipleSelection.value.length === 0) {
    ElMessage.warning("未选择目标");
    return;
  }
  const ids = multipleSelection.value.reduce(
    (acc, item) => [...acc, item.resident_id],
    []
  );
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteResidentMoreByIdAPI(ids).then((res) => {
        const { code, message } = res.data;
        getResidentPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};

/* 查询 */
const SearcSelect = [
  { label: "身份证号", prop: "resident_id" },
  { label: "户主", prop: "family_master" },
  { label: "姓名", prop: "name" },
  { label: "年龄", prop: "age" },
  { label: "性别", prop: "gender" },
  { label: "出生时间", prop: "date_of_birth" },
  { label: "家庭位置", prop: "relationship" },
  { label: "电话", prop: "phone" },
  { label: "地址", prop: "address" },
  { label: "登记时间", prop: "registration_date" },
  { label: "备注", prop: "notes" },
];
const SearchResidentList = () => {
  console.log(SearchResident.selectKey);
  if (!SearchResident.searchValue) {
    getResidentPage();
    return;
  }

  
  loading.value = true;
  getResidentKeyPageAPI({
    SearchKey: SearchResident.selectKey,
    SearchValue: SearchResident.searchValue,
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "resident_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      row.forEach((item) => {
        item.date_of_birth = formatDate(item.date_of_birth);
        item.registration_date = formatDate(item.registration_date);
      });
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};

// 监听分页
watch(
  () => page.currentPage,
  () => {
    if (!SearchResident.searchValue) {
      getResidentPage();
    } else {
      SearchResidentList()
    }
  }
);
onMounted(() => {
  setTimeout(() => {
    getResidentPage();
  }, 1000);
});
</script>
<style scoped lang="scss">
.Box {
  position: relative;

  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }

    .searchBtn {
      color: rgb(15, 153, 245);
    }

    .addBtn {
      margin-right: 1rem;
    }
  }

  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }

  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }

    :deep(.status-active) {
      color: green;
    }

    :deep(.status-unactive) {
      color: #f56c6c;
    }

    :deep(.OptionsBtn) {
      height: 30px;
      line-height: 30px;
      width: 8.125rem;
      border: 1px solid #f56c6c;
      border-radius: 0.3rem;
      text-align: center;
      background-color: #f56c6c;
      color: #fff;
      cursor: pointer;

      &:hover {
        background-color: #e78d8d;
        border: 1px solid #e78d8d;
      }
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>
